<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
       <!-- <el-table-column label="供应商编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.supplierId`" :rules="formRules.supplierId" class="mb-0px!">
            <el-input v-model="row.supplierId" placeholder="请输入供应商编号" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="产品编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-input v-model="row.productId" placeholder="请输入产品编号" />
          </el-form-item>   
        </template>
      </el-table-column> -->

          <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              disabled
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>


      <!-- <el-table-column label="产品名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productName`" :rules="formRules.productName" class="mb-0px!">
            <el-input v-model="row.productName" placeholder="请输入产品名称" />
          </el-form-item>   
        </template>
      </el-table-column> -->

      <el-table-column label="产品单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productUnit`" :rules="formRules.productUnit" class="mb-0px!">
            <el-input v-model="row.productUnit" placeholder="请输入产品单位" readonly/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productStandards`" :rules="formRules.productStandards" class="mb-0px!">
            <el-input v-model="row.productStandards" placeholder="请输入产品规格" readonly/>
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="产品单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" :rules="formRules.productPrice" class="mb-0px!">
            <el-input v-model="row.productPrice" placeholder="请输入产品单价" />
          </el-form-item>
        </template>
      </el-table-column> -->

      <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0.01"
              disabled
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>


      <!-- <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input v-model="row.count" placeholder="请输入数量" />
          </el-form-item>
        </template>
      </el-table-column> -->

       <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              disabled
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>



      <!-- <el-table-column label="总价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" :rules="formRules.totalPrice" class="mb-0px!">
            <el-input v-model="row.totalPrice" placeholder="请输入总价" />
          </el-form-item>
        </template>
      </el-table-column> -->

        <el-table-column label="总价" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input
              disabled
              v-model="row.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </template>
      </el-table-column>

      <!-- <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-form>
  <!-- <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加ERP 科室采购申请项</el-button>
  </el-row> -->
</template>
<script setup lang="ts">
import { DepPurchaseApi } from '@/api/erp/deppurchase'

import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { SecStockApi } from '@/api/erp/secstock'
import { StockApi } from '@/api/erp/stock/stock'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'


const props = defineProps<{
  orderId: undefined // 科室采购订单编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  orderId: [{ required: true, message: '科室采购订单编号不能为空', trigger: 'blur' }],
  // supplierId: [{ required: true, message: '供应商编号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productUnit: [{ required: true, message: '产品单位不能为空', trigger: 'blur' }],
  productStandards: [{ required: true, message: '产品规格不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  totalPrice: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const productOptions = ref([])

// /** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.orderId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await DepPurchaseApi.getDepPurchaseItemListByOrderId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
  
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      if (item.totalProductPrice != null) {
        item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)


/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'productPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  }) 

  return sums
}

/** 新增按钮操作 */
const handleAdd = async () => {
    productOptions.value = await SecStockApi.getSecStockListByDeptId(deptId)
  const row = {
    id: undefined,
    orderId: undefined,
    supplierId: undefined,
    productId: undefined,
    productUnit: undefined,
    productStandards: undefined,
    productPrice: undefined,
    count: 1,
    totalPrice: undefined,
    remark: undefined,
    proudctName: undefined,
  }
  row.orderId = props.orderId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}


/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productOptions.value.find((item) => item.id === productId)

  if (product) {
    row.productStandards = product.productStandards //产品规格
    row.productUnit = product.productUnit //产品单位
    row.productPrice = product.productPrice //产品单价
    // console.log(product.standard,'8848')

  }
  // 加载库存
  setStockCount(row)
}




/** 加载库存 */
const setStockCount = async (row: any) => {
  if (!row.productId) {
    return
  }
  const count = await StockApi.getStockCount(row.productId)
  row.stockCount = count || 0
}




/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})

// 定义一个全局变量 deptId
let deptId: number
onMounted(() => {
  const Info = JSON.parse(localStorage.getItem('user') || '{}')
  const userInfo = JSON.parse(Info.v)
  deptId = userInfo.user.deptId
 
})

defineExpose({ validate, getData })
</script>